package com.weareint.common.utils;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.weareint.common.constants.Constants;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

public abstract class PageUtil {

    public static <T, S> Page<T> convertPage(Page<S> src, Function<? super S, ? extends T> mapper){
        List<T> dtos = src.getRecords().stream().map(mapper).collect(Collectors.toList());
        Page<T> dest = new Page<>();
        dest.setRecords(dtos).setSize(src.getSize())
                .setCurrent(src.getCurrent())
                .setOptimizeCountSql(src.isOptimizeCountSql())
                .setSearchCount(src.isSearchCount())
                .setTotal(src.getTotal());
        return dest;
    }

    public static <T> Page<T> toPage(List<T> records, int page, int size, long total){
        Page<T> dest = new Page<>();
        dest.setRecords(records).setSize(size)
                .setCurrent(page)
                .setTotal(total);
        return dest;
    }

    public static <T> Page<T> createPageable(Integer page, Integer size){
        if (null == page || page <= 0){
            page = Constants.PAGE_START;
        }
        if (null == size || size <= 0 || size > Constants.PAGE_MAX_SIZE){
            size = Constants.PAGE_DEFAULT_SIZE;
        }
        return new Page<T>(page, size);
    }

}
